package ssh

import (
    LinuxShell "../shell"
    "fmt"
    "path"
    "strconv"
    "strings"
    "time"
)

type SysSSH struct {
    User string
    Host string
    Port int
}

func (ssh SysSSH) Exe(cmdr ...string) SSHResult {
    args := make([]string, 0)
    if ssh.Port != 0 && ssh.Port != 22 && ssh.Port > 0 {
        args = append(args, "-p", strconv.Itoa(ssh.Port))
    }
    args = append(args, fmt.Sprintf("%s@%s", ssh.User, ssh.Host))
    args = append(args, strings.Join(cmdr, ";"))
    return ssh.do("ssh", args...)
}

func (ssh SysSSH) Upload(localFile string, targetDir string) SSHResult {
    args := make([]string, 0)
    //args = append(args, "scp")
    if ssh.Port != 0 && ssh.Port != 22 && ssh.Port > 0 {
        args = append(args, "-P", strconv.Itoa(ssh.Port))
    }
    args = append(args, localFile, fmt.Sprintf("%s@%s:%s", ssh.User, ssh.Host, targetDir))
    return ssh.do("scp", args...)
}

func (ssh SysSSH) do(name string, args ...string) SSHResult {
    result := SSHResult{}
    shell := LinuxShell.LinuxShell{Name: name, Args: args}
    sResult := shell.Exe()
    result.StdOut = sResult.Stdout.String()
    result.StdErr = sResult.Stderr.String()
    if sResult.Error != nil {
        result.Code = -1
    }
    return result
}

func (ssh SysSSH) UploadVisible(localFile, targetDir, tmpDir string) SSHResult {
    result := SSHResult{}
    args := make([]string, 0)
    args = append(args, "scp")
    if ssh.Port != 0 && ssh.Port != 22 && ssh.Port > 0 {
        args = append(args, "-P", strconv.Itoa(ssh.Port))
    }
    args = append(args, localFile, fmt.Sprintf("%s@%s:%s", ssh.User, ssh.Host, targetDir))
    scpCommand := strings.Join(args, " ")
    fmt.Println(scpCommand)
    args = make([]string, 0)
    tempLogFile := path.Join(tmpDir, fmt.Sprintf("scp-%d.log", time.Now().Unix()))
    args = append(args, "script", "-q", "-c", fmt.Sprintf("\"%s\"", scpCommand),">",tempLogFile)
    return result
}
